<template>
  <div class="container">
      <!-- 返回箭头，标题，分享icon -->
      <van-nav-bar
        fixed
        class="title"
        title="商品详情"
        left-arrow
        @click-left="onClickLeft"
        :style="{ '--van-nav-bar-arrow-size': '20px'}"
      >

        <template #right>
          <van-icon
            name="share-o"
            size="25"
            style="margin-right: 8px;"
            @click="handleShare"
          />
        </template>
      </van-nav-bar>

      <!-- 商品图片 -->
      <van-image
        class="imageurl"
        v-if="product.imageUrl"
        :src="product.imageUrl"
        fit="cover"
      />
      <!-- 商品基本信息 -->
      <div class="product-info">
        <van-cell-group inset class="info1">
          <van-cell class="no-bottom-border">
          <template #title>
              <!-- 商品名称 -->
              <h2 class="product-title">{{ product.productName }}</h2>
              <!-- 商品价格 -->
              <p class="product-price">¥ {{ product.price?.toFixed(2) }}</p>
              <!-- 规格信息 -->
              <div class="specs-wrap">
                <div class="specs">
                <span class="spec-label">规格：</span>
                <van-tag
                  class="spec-tag"
                  v-for="(specItem, index) in specs"
                  :key="index"
                  type="default"
                  :closable="false"
                >{{ specItem }}</van-tag>
                </div>
                <!-- 更多选择按钮 -->
                <div class="more-specs" @click="showSpecPopup = true">
                更多选择
                <van-icon name="arrow" class="spec-arrow" />
                </div>

              </div>
          </template>
          </van-cell>

          <van-cell>
          <template #title>
            <van-cell-group inset class="desc-cell-group">
            <!-- 商品描述 -->
            <p class="product-desc">{{ product.description }}</p>
            </van-cell-group>
          </template>
          </van-cell>
        </van-cell-group>

        <van-cell-group inset class="info2">
          <van-cell class="no-bottom-border1" title="商品评价" :value="`(${commentCount})`">
          </van-cell>

          <van-cell
            is-link
            @click="goToComment"
            class="no-comment-cell"
          >
            <template #title>
              <div class="no-comment-card">
              <span class="comment-text">暂无评价</span>
              <van-icon name="arrow" class="comment-arrow" />
              </div>
            </template>
          </van-cell>
        </van-cell-group>

        <!-- 商品详情 -->
        <div class="detail-title-wrap">
          <span class="divider-line"></span>
          <span class="detail-title-text">商品详情</span>
          <span class="divider-line"></span>
        </div>

        <!-- 详情图片 -->
        <div class="detail-image-card">
          <van-image
            v-if="product.detailImageUrls && product.detailImageUrls.length"
            v-for="(imgUrl, index) in product.detailImageUrls"
            :key="index"
            :src="product.imageUrl"
            fit="cover"
            class="detail-image"
          />
          <!-- 没有详情图片时显示默认提示 -->
          <div v-else class="no-detail-image">
            <van-icon name="picture-o" size="40" color="#ccc" />
            <p class="no-image-text">暂无详情图片</p>
          </div>
       </div>

      <!-- 规格选择弹窗 1-->
      <van-popup v-model:show="showSpecPopup" position="bottom" round>
          <div class="spec-popup">
             <!-- 顶部商品信息区域 -->
             <div class="popup-header">
                <van-image
                :src="product.imageUrl"
                fit="cover"
                class="product-thumbnail"
              />

              <div class="price-and-spec">
                <div class="price">¥ {{ product.price?.toFixed(2) }}</div>
                <div class="selected-spec">已选择：{{  specs.join('/') }}</div>
               </div>
              <van-icon name="close" class="close-icon" @click="showSpecPopup = false" />
             </div>

            <!-- 颜色,材质,尺寸 -->
            <div
              v-for="(group, groupIndex) in specGroups"
              :key="groupIndex"
              class="spec-section"
            >
              <h3>{{ group.name }}</h3>

              <div class="custom-radio-group">
                <van-button
                   v-for="(option, optIndex) in group.options"
                  :key="optIndex"
                  type="default"
                  size="small"
                  :class="{
                  'custom-radio-btn': true,
                  'is-checked': selectedValues[group.name] === option
                  }"
                 @click="() => selectedValues[group.name] = option"
                  >
                  {{ option }}
                </van-button>
              </div>
            </div>

            <!-- 购买按钮 -->
            <div class="spec-actions">
                <van-button
                class="buy-btn-1"
                size="large"
                @click="handleBuy"
                >立即购买</van-button>
            </div>
        </div>
      </van-popup>


      <!-- 规格选择弹窗 2-->
      <van-popup v-model:show="showSpecPopup2" position="bottom" round>
          <div class="spec-popup">
             <!-- 顶部商品信息区域 -->
             <div class="popup-header">
                <van-image
                :src="product.imageUrl"
                fit="cover"
                class="product-thumbnail"
              />

              <div class="price-and-spec">
                <div class="price">¥ {{ product.price?.toFixed(2) }}</div>
                <div class="selected-spec">已选择：{{  specs.join('/') }}</div>
               </div>
              <van-icon name="close" class="close-icon" @click="showSpecPopup2 = false" />
             </div>

            <!-- 颜色,材质,尺寸 -->
            <div
              v-for="(group, groupIndex) in specGroups"
              :key="groupIndex"
              class="spec-section"
            >
              <h3>{{ group.name }}</h3>

              <div class="custom-radio-group">
                <van-button
                   v-for="(option, optIndex) in group.options"
                  :key="optIndex"
                  type="default"
                  size="small"
                  :class="{
                  'custom-radio-btn': true,
                  'is-checked': selectedValues[group.name] === option
                  }"
                 @click="() => selectedValues[group.name] = option"
                  >
                  {{ option }}
                </van-button>
              </div>
            </div>

            <!-- 购买按钮 -->
            <div class="spec-actions">
                <van-button
                class="buy-btn-1"
                size="large"
                @click="handleBuy"
                >立即购买</van-button>
            </div>
        </div>
      </van-popup>

      <!-- 底部固定区域，包含头像、价格、立即购买按钮 -->
      <div class="bottom-fixed-bar">
        <!-- 头像 -->
        <van-image
          round
          :src="avatarUrl"
          class="avatar"
        />
        <!-- 价格 -->
        <span class="price">¥ {{ product.price?.toFixed(2) }}</span>
        <!-- 立即购买按钮 -->
        <van-button
          class="buy-btn"
          size="large"
          @click="showSpecPopup2 = true"
        >立即购买</van-button>
      </div>

    </div>
  </div>
</template>

<script setup name="ProductDetail">
import { ref, onMounted, computed } from 'vue';
import { useRouter , useRoute } from 'vue-router';
import { selectProdetailById } from '../api/index';
import avatarImg from '../assets/lianxiwo.png';
import imgurl from '../assets/yinshuiji.png';
import { useOrderStore } from '../stores/order';
import {useUserInfoStore}  from '../stores/userInfo'

const orderStore = useOrderStore();
const userInfoStore= useUserInfoStore();

const userId = userInfoStore.userId

// 定义响应式数据
const product = ref({})
const commentCount = ref(0)
const router = useRouter()
const route = useRoute()
const avatarUrl = ref(avatarImg)
const imgUrl = ref(imgurl)
const showSpecPopup = ref(false)
const showSpecPopup2 = ref(false)
const selectedValues = ref({})
const specGroups = ref([])

// 从后端获取商品详情数据的函数
const getProductDetail = async () => {
  const productId = route.query.id;
  if (!productId) {
    console.error('未获取到商品ID');
    return;
  }

  let ret = await selectProdetailById(productId)
  product.value = ret

  if (product.value.spec) {
    // 按分号分割规格组（颜色组;材质组;尺寸组）
    const specArray = product.value.spec.split(';');

    // 定义规格组配置（顺序与后端返回保持一致）
    const specTypes = [
      { name: '颜色', separator: ',' },  // 颜色用逗号分隔
      { name: '材质', separator: ',' },  // 材质用逗号分隔
      { name: '尺寸', separator: ',' }   // 尺寸用逗号分隔
    ];

    // 解析每个规格组
    specGroups.value = specArray.map((specItem, index) => {
      const specType = specTypes[index] || { name: '规格', separator: ',' };
      // 按对应分隔符分割选项
      const options = specItem.split(specType.separator).map(option => option.trim());
      return {
        name: specType.name,
        options: options
      };
    });
    // 自动选中每个规格组的第一个选项
    specGroups.value.forEach(group => {
      if (group.options && group.options.length > 0) {
        selectedValues.value[group.name] = group.options[0];
      }
    });
  }

  // 设置详情图片
  product.value.detailImageUrls = [imgUrl.value];
}

// 确认规格选择
const confirmSpec = () => {
  showSpecPopup.value = false;
  showSpecPopup2.value = false;
}

// 计算当前选中的规格
const specs = computed(() => {
  return specGroups.value.map(group => selectedValues.value[group.name] || '');
})

// 
const handleBuy = () => {
 
  const productData = {
    productId: product.value.productId,
    productName: product.value.productName,
    price: product.value.price,
    imageUrl: product.value.imageUrl || imgUrl.value,
    spec: specs.value.filter(Boolean).join('/'),
    deliveryDesc: product.value.deliveryDesc || '20天内发货',
    quantity: 1
  };
   // 跳转前清空状态管理中的旧数据
  orderStore.clearCartItems(); // 需在 orderStore 中新增清空方法
  router.push({
    name: 'checkOrder',
    query: {
      productData: JSON.stringify(productData)
    }
  })
}

const onClickLeft = () => {
  router.push({ name: "petShop" })
}

const handleShare = () => {
  // 分享功能实现
}

const goToComment = () => {
  // 跳转到评价页面
}

onMounted(() => {
  getProductDetail();
})
</script>

<style lang='less' scoped>
.container{
  background-color: rgb(245, 243, 243)
}

.imageurl{
  width: 100%;
  height: 350px;
  margin-top: 46px;
}

.info1{
  margin-top: -8px;
}

.info2{
  margin-top: 15px;
}

.product-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.desc-cell-group {
  padding: 5px 10px;
  margin: 0px ;
  background-color: #f5f5f5;
  border-radius: 6px;
  font-size: 15;
  color: #66666680;
}

.product-desc {
  margin: 0;
  line-height: 2.0;
}

.product-price {
  font-size: 20px;
  color: #f00;
  margin-bottom: 20px;
  text-align: left;
}

.specs {
  display: flex;
  align-items: center;
}

.spec-label {
  margin-right: 8px;
}

.specs-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.more-specs {
  display: flex;
  align-items: center;
  color: #999;
  cursor: pointer;
}

.spec-arrow {
  margin-left: 4px;
  font-size: 14px;
}

::v-deep .no-bottom-border::after {
  display: none;
}

::v-deep .no-bottom-border1::after {
  display: none;
}

.no-comment-cell {
  padding: 3px 16px;
}

.no-comment-card {
  background-color: #FFF9C4;
  width: 100%;
  height: 50%;
  padding: 5px 12px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.comment-text {
  color: #A0522D;
  font-size: 12px;
}

.comment-arrow {
  color: #A0522D;
  font-size: 12px;
}

.detail-title-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  padding: 0 16px;
}

.divider-line {
  flex: 1;
  height: 1px;
  background-color: #dfdada;
}

.detail-title-text {
  color: #999;
  font-size: 14px;
  padding: 0 12px;
  white-space: nowrap;
}

.detail-image-card {
  margin: 0 16px 20px;
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.detail-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin-bottom: 12px;
}

.no-detail-image {
  text-align: center;
  padding: 30px 0;
  color: #ccc;
}

.bottom-fixed-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 10px 16px;
  box-sizing: border-box;
}

.avatar {
  width: 50px;
  height: 45px;
  margin-right: 8px;
}

.price {
  font-size: 16px;
  color: black;
  margin-right: auto;
}

.buy-btn {
  position: fixed;
  bottom: 10px;
  right: 5px;
  width: 5px;
  border: none;
  background-color: #FFD700;
  color: #333;
  border-radius: 30px;
  padding: 14px 32px;
  min-width: 120px;
  font-weight: bold;
  font-size: 14px;
}

.spec-popup {
  padding: 16px;
}

.spec-section {
  margin-bottom: 20px;
}

.spec-section h3 {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.spec-actions {
  text-align: center;
  margin-top: 20px;
}

.spec-tag {
  background-color: #f5f5f5 !important;
  color: #333 !important;
  border: none !important;
  margin-right: 10px;
  padding: 4px 10px;
}

.popup-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px;
}

.product-thumbnail {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  margin-top: 5px;
}

.price-and-spec {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 10px;
  flex: 1;
}

.price {
  margin-top: 15px;
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
}

.selected-spec {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.close-icon {
  font-size: 20px;
  color: #999;
  cursor: pointer;
  align-self: flex-start;
}

.custom-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.custom-radio-btn {
  border: 1px solid #d9d9d9 !important;
  width: 78px;
  height: 43px;
  border-radius: 5px !important;
  color: #999 !important;
  background: #fff !important;
  font-size: 14px !important;
  transition: all 0.2s !important;
}

.custom-radio-btn.is-checked {
  border: 1px solid #fb7a02 !important;
  color: #ff7d00 !important;
  background: white !important;
}

.custom-radio-btn:not(.is-checked):hover {
  border: 1px solid #bfbfbf !important;
  color: #666 !important;
}

.buy-btn-1{
  width: 80%;
  background-color: #FFD700;
  font-weight: bold;
  border-radius: 30px;
  padding: 14px 32px;
  min-width: 200px;
  font-size: 14px;
  text-align: center;
  margin: 0 auto;
  display: block;
}
</style>
